package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.ResponseProcessorImp;

import java.util.Date;
import java.util.concurrent.BlockingQueue;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressValue;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.procimg.InputRegister;

public class ReadInputRegisterResponseProcessor extends
		AbstractResponseProcessor {

	@Override
	public void processResponse(ModbusRequest req, ModbusResponse res, BlockingQueue<AddressValue> queue) {
		// TODO ReadInputRegisterResponseProcessor error IllegalAddressException
		if(res instanceof ReadInputRegistersResponse && req instanceof ReadInputRegistersRequest){
			
			InputRegister[] regs = ((ReadInputRegistersResponse) res).getRegisters();
			int baseDir = ((ReadInputRegistersRequest) req).getReference();
			int regCount = ((ReadInputRegistersRequest) req).getWordCount();
			Date date = new Date();
			
			for(int i = 0; i < regCount; i++){
				
				int address = baseDir + i;
				InputRegister value = regs[i];
				
				AddressValue newValue = new AddressValue();
				newValue.setAddress(address);
				newValue.setAddressType(AddressType.INPUT_REGISTER);
				newValue.setDate(date);
				newValue.setValue(value.getValue());
				
				queue.add(newValue);
				
				getImage().setInputRegister(address,value,date);
				//TODO:Descomentar
				/*
				if( getDeciveDAO() != null )
						getDeciveDAO().saveValue( getDevice(), address , value.getValue() , AddressType.INPUT_REGISTER );
				*/	
			}
			
		}
	}

}
